package com.jeeplus.test.jlnu.admissionInfo.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.jeeplus.test.education.domain.vo.EducationInfoVo;
import com.jeeplus.test.jlnu.admissionInfo.service.ContinueService;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.*;

public class ContinueDataListener extends AnalysisEventListener<EducationInfoVo> {

    private final ContinueService excelServiceStu;
    private final MyWebSocketHandler webSocketHandler;  // 使用 MyWebSocketHandler
    private static final int BATCH_COUNT = 500;
    private final String officeId;
    private List<EducationInfoVo> dataList = new ArrayList<>();
    private int totalRecords;
    private int currentRecords;
    private final String importType;
    private String templateInfoType;
    private  int templateId;

    // 【新增】用于记录已存在的考生号（ksh）
    private Set<String> kshSet = new HashSet<>();

    // 【新增】存储重复的数据（最终汇总到前端）
    private List<EducationInfoVo> duplicates = new ArrayList<>();


    public ContinueDataListener(ContinueService excelServiceStu, int totalRecords, String officeId,
                                String importType,String templateInfoType, MyWebSocketHandler webSocketHandler,int templateId1) {
        this.excelServiceStu = excelServiceStu;
        this.totalRecords = totalRecords;
        this.officeId = officeId;
        this.importType = importType;
        this.templateInfoType = templateInfoType;
        this.webSocketHandler = webSocketHandler; // 保存 MyWebSocketHandler 实例
        this.templateId = templateId1; // 保存 MyWebSocketHandler 实例
    }

    @Override
    public void invoke(EducationInfoVo data, AnalysisContext context) {
        try {
            int currentRow = context.readRowHolder().getRowIndex();
            if (currentRow == 1) {
               // return; // 跳过第二行
            }
            data.setOfficeId(officeId);
            dataList.add(data);
            currentRecords++;

            if (dataList.size() >= BATCH_COUNT) {
                saveDataToDatabase();
                dataList.clear();
            }

            updateProgress();
        } catch (Exception e) {
            sendErrorMessage("导入过程中发生错误: " + e.getMessage());
        }
    }




    // 【新增】发送单条重复数据的方法
    private void sendDuplicateMessage(EducationInfoVo data) {
        try {
            WebSocketSession session = webSocketHandler.getFirstWebSocketSession();
            if (session != null && session.isOpen()) {
                // 【修改】JSON格式字符串中添加类型标识
                Map<String, Object> message = new HashMap<>();
                message.put("type", "duplicate");
                message.put("data", data);
                session.sendMessage(new TextMessage(JSON.toJSONString(message)));        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}










    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        try {
            if (!dataList.isEmpty()) {
                saveDataToDatabase();
                dataList.clear();
            }
            // 【新增】处理所有重复数据并发送最终列表
            if (!duplicates.isEmpty()) {
                WebSocketSession session = webSocketHandler.getFirstWebSocketSession();

                //创建消息容器
                Map<String, Object> message = new HashMap<>();
                message.put("type", "all_duplicates");
                message.put("data", duplicates);

                //序列化为 JSON 字符串
                String jsonString = JSON.toJSONString(message);
                // 发送消息
                session.sendMessage(new TextMessage(jsonString));
        }
            updateProgress();
        } catch (Exception e) {
            sendErrorMessage("导入发生错误: " + e.getMessage());
        }
    }

    private void saveDataToDatabase() {
        if (!dataList.isEmpty()) {
            excelServiceStu.insertDataStu(dataList,importType,templateInfoType,officeId, templateId);
        }
    }

    private void updateProgress() {
        int progress = (int) (((double) currentRecords / totalRecords) * 100);
        sendProgressUpdate(progress);
    }

    private void sendProgressUpdate(int progress) {
        try {
            WebSocketSession webSocketSession = webSocketHandler.getFirstWebSocketSession();  // 获取第一个 WebSocketSession
            if (webSocketSession != null && webSocketSession.isOpen()) {
                webSocketSession.sendMessage(new TextMessage("{\"type\": \"progress\", \"progress\": " + progress + "}"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void sendErrorMessage(String message) {
        try {
            WebSocketSession webSocketSession = webSocketHandler.getFirstWebSocketSession();  // 获取第一个 WebSocketSession
            if (webSocketSession != null && webSocketSession.isOpen()) {
                webSocketSession.sendMessage(new TextMessage("{\"type\": \"error\", \"message\": \"" + message + "\"}"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
